import Vue from 'vue'
import VueRouter from 'vue-router'
// Vuex 实例
import store from '@/store'

const Login = () => import('@/views/Login/index.vue')
// 主页容器
const Layout = () => import('@/views/Layout/index.vue')
// home首页
const Home = () => import('@/views/Home/index.vue')
// 个人中心
const User = () => import('@/views/User/index.vue')
// 搜索中心
const SearchIndex = () => import('@/views/Search/index.vue')
// 搜索结果
const SearchResult = () => import('@/views/Search/SearchResult.vue')
// 文章详情
const ArticleDetails = () => import('@/views/ArticleDetail/ArticleDetails.vue')
// 用户编辑
const EditUser = () => import('@/views/User/EditUser.vue')
// 小智同学
const Chat = () => import('@/views/User/Chat.vue')
Vue.use(VueRouter)

// 解决 router bug
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    children: [
      // home是主页可以不用写就是 /
      { path: '', name: 'home', component: Home },
      { path: '/user', name: 'user', component: User }
    ]
  },
  { path: '/searchIndex', name: 'searchIndex', component: SearchIndex },
  { path: '/searchResult', name: 'searchResult', component: SearchResult },
  { path: '/articleDetails', name: 'articleDetails', component: ArticleDetails },
  { path: '/editUser', name: 'editUser', component: EditUser },
  { path: '/chat', name: 'chat', component: Chat }
]

const router = new VueRouter({
  routes
})

// 允许的token的列表
const permissionList = ['/user', '/EditUser']
// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to: 要去哪里
  // from: 从哪里去
  // next： 方法，进行管道中的下一个钩子
  // if () {}
  // 包含列表中的路径，就需要判断 token 是否存在，不存在就需要跳转到登录页
  if (permissionList.includes(to.path)) {
    const token = store.state.tokenInfo
    if (token && token.token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          backto: to.fullPath // 从哪儿跳转来的
        }
      })
    }
  } else { // 不被包含的就放行
    next()
  }
})

export default router
